﻿using AutoMapper;
using MediatR;
using SCM.API.Write.Application.Command.Purchase;
using SCM.API.Write.Application.Command.PurchaseRefund;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Implement;
using SCM.Infrastructure.Interface;

namespace SCM.API.Write.Application.Handler.PurchaseRefund
{
    public class DelPurchaseRefundHandler : IRequestHandler<DelPurchaseRefundCommand, APIResult<int>>
    {
        DatabaseContext db;
        IMapper mapper;
        ILogger<DelPurchaseRefundHandler> logger;
        public DelPurchaseRefundHandler(IMapper mapper, DatabaseContext db, ILogger<DelPurchaseRefundHandler> logger)
        {
            this.mapper = mapper;
            this.db = db;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(DelPurchaseRefundCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var res = db.SqlSugar.Queryable<PurchaseRefundModel>().Where(x => x.Id == request.Id).First();
                res.IsDel = true;
                int r = db.SqlSugar.Updateable(res).ExecuteCommand();
                if (r > 0)
                {
                    result.Msg = "删除采购退货单信息成功";
                    result.Data = r;
                    result.Code = APIEnum.Success;
                }
                else
                {
                    result.Msg = "删除采购退货单信息失败";
                    result.Data = r;
                    result.Code = APIEnum.Fail;
                }
                return Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "处理采购退货删除命令时发生异常");
                throw;
            }
        }
    }
}
